import { defineStore } from "pinia";
import {
  ISeriesData,
} from "@renderer/store/pinia/type";
import { idHelper } from "@renderer/store/pinia/helper";

const useDicomDataStore = defineStore("dicomData", {
  state: () => {
    return {
      patientRecord: {
      } as Record<string, any>,
      seriesRecord: {

      } as Record<string | number, ISeriesData>,
      selectedSeriesUIDArr: [] as string[],
      openedPatientUID: [] as any[]
    };
  },

  actions: {
    appendSelectedSeriesUIDArr(seriesUID){
      if (!this.selectedSeriesUIDArr.includes(seriesUID)) {
        this.selectedSeriesUIDArr.push(seriesUID);
      }
    },
    getSeriesUID(patientUID, seriesId) {
      return `${patientUID}|${seriesId}`;
    },
    parseSeriesUID(seriesUID) {
      const arr = seriesUID.split("|");
      return {
        patientUID: arr[0],
        seriesId: arr[1],
      }
    },
    /*
    * 根据后端数据更新患者列表和扫描序列列表。
    * */
    updatePatientAndSeriesRecord(patientRecord, seriesRecord){
        for(const [patientUID, patientInfo] of Object.entries(patientRecord) as any) {
          this.openedPatientUID.push(patientInfo.patientName);
          if (this.patientRecord[patientUID]){
             this.patientRecord[patientUID].seriesIds = Array.from(new Set([...patientInfo.seriesIds,
                                                                                   ...this.patientRecord[patientUID].seriesIds]))
          }else {
            Object.assign(this.patientRecord, patientRecord);
          }
        }
        Object.assign(this.seriesRecord, seriesRecord);
    },
    updateSelectedSeriesUIDByActiveTab(tabId: string) {
      const {patientUID,seriesId} = idHelper.resolveTabId(tabId);
      const seriesUID = this.getSeriesUID(patientUID, seriesId);
      if (!this.selectedSeriesUIDArr.includes(seriesUID)) {
        this.selectedSeriesUIDArr = [seriesUID];
      }
    },
    removeSeries(seriesId){
       delete this.seriesRecord[seriesId];
       for (const[patientUID, record] of Object.entries(this.patientRecord)) {
         const index = record.seriesIds.indexOf(seriesId);
         if (index !== -1){
           record.seriesIds.splice(index, 1);
           if (record.seriesIds.length === 0){
             delete this.patientRecord[patientUID];
           }
           break;
         }
       }
    }
  },
});

export { useDicomDataStore };
